package com.rain.shoppingscienceproj.ui.activity.car;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rain.shoppingscienceproj.R;
import com.rain.shoppingscienceproj.http.BaseSubscriber;
import com.rain.shoppingscienceproj.http.ExceptionHandle;
import com.rain.shoppingscienceproj.http.RetrofitClient;
import com.rain.shoppingscienceproj.module.CarData;
import com.rain.shoppingscienceproj.module.ShoppingcarDto;
import com.rain.shoppingscienceproj.ui.activity.BaseActivity;
import com.rain.shoppingscienceproj.ui.activity.login.LoginActivity;
import com.rain.shoppingscienceproj.ui.activity.order.MakeOrderActivity;
import com.rain.shoppingscienceproj.ui.adapter.CarAdapter;
import com.rain.shoppingscienceproj.ui.base.GlobalData;
import com.rain.shoppingscienceproj.ui.utile.DialogUtils;
import com.rain.shoppingscienceproj.ui.utile.TitleUtils;
import com.rain.shoppingscienceproj.utils.AppManager;
import com.rain.shoppingscienceproj.utils.LoadingDialog;
import com.rain.shoppingscienceproj.utils.toast.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;

public class ShoppingCarActivity extends BaseActivity {


    @BindView(R.id.rv_data)
    RecyclerView mRecyclerView;
    @BindView(R.id.iv_check)
    ImageView iv_check;
    @BindView(R.id.tv_total_num)
    TextView tv_total_num;
    @BindView(R.id.tv_money)
    TextView tv_money;
    double doubleGoodsMoney = 0.00;
    int goodsNum = 0;
    DecimalFormat df = new DecimalFormat("#.00");

    ArrayList<CarData> selectCarDataList = new ArrayList<>();
    //    List<MyCarData> carDataList;
    @BindView(R.id.ll_no_data)
    LinearLayout ll_no_data;

//    List<ShoppingcarDto> goodsList = new ArrayList<>();
//    Map<String, Integer> map = new HashMap<>();

    List<CarData> carData;
    private CarAdapter carAdapter;
    private boolean isAllSelect = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_car);
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        TitleUtils.TitleView(this, "我的购物车");
        userInfo = GlobalData.getUserInfo();
        loadingDialog = new LoadingDialog(this, "正在加载...");
        initView();
        initData();
        initListener();
    }

    private void initListener() {
        carAdapter.setCheckItemClickListener((myCarData, isGoodsAllSelect) -> {
            if (selectCarDataList.size() > 0) {
                for (int i = 0; i < selectCarDataList.size(); i++) {
                    if (selectCarDataList.get(i).getShop().getShopId().equals(myCarData.getShop().getShopId())) {
                        selectCarDataList.remove(i);
                    }
                }
                if (myCarData.getList().size() > 0) {
                    selectCarDataList.add(myCarData);
                }

            } else {
                selectCarDataList.add(myCarData);
            }

            if (isGoodsAllSelect) {
                isAllSelect = true;
                iv_check.setImageResource(R.drawable.address_complete);
            } else {
                isAllSelect = false;
                iv_check.setImageResource(R.drawable.wallet_recharge_checkbox);
            }
            count();
        });

        carAdapter.setCountListenter((money, isOperation, isRole) -> {
            if (isRole) {
                if (isOperation) {
                    doubleGoodsMoney += Double.valueOf(money);
                } else {
                    doubleGoodsMoney -= Double.valueOf(money);
                }
                if (doubleGoodsMoney < 1) {
                    tv_money.setText(0 + df.format(doubleGoodsMoney));
                } else {
                    tv_money.setText(df.format(doubleGoodsMoney));
                }
            }
        });

        carAdapter.setLongItemListener((shopId, goodsId, position) -> {
            DialogUtils.dialog(this, "确定删除该商品吗?");
            DialogUtils.getTv_sure().setOnClickListener(v -> delCar(shopId, goodsId));
        });
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        initData();
        selectCarDataList.clear();
        isAllSelect = false;
        iv_check.setImageResource(R.drawable.wallet_recharge_checkbox);
        tv_total_num.setText("共计" + 0 + "件商品 ");
        tv_money.setText("0.00");
    }

    private void initData() {
        if (userInfo != null) {
            Map<String, String> map = new HashMap<>();
//            map.put("userId", userInfo.getUserId());
            map.put("token", userInfo.getToken());
            loadingDialog.show();
            RetrofitClient.getInstance(this)
                    .createBaseApi()
                    .queryCarList(map, new BaseSubscriber<List<CarData>>(this) {
                        @Override
                        public void onError(ExceptionHandle.ResponeThrowable e) {
                            if (e.Message.contains("token")) {
                                startActivitys(LoginActivity.class, 1);
                            }
                            ToastUtils.showShortToast(e.Message);
                            loadingDialog.dismiss();
                            ll_no_data.setVisibility(View.VISIBLE);
                            mRecyclerView.setVisibility(View.GONE);
                        }

                        @Override
                        public void onNext(List<CarData> myCarDataList) {
                            super.onNext(myCarDataList);
                            loadingDialog.dismiss();
                            if (myCarDataList.size() == 0) {
                                ll_no_data.setVisibility(View.VISIBLE);
                                mRecyclerView.setVisibility(View.GONE);
                            } else {
                                ll_no_data.setVisibility(View.GONE);
                                mRecyclerView.setVisibility(View.VISIBLE);
                            }
                            carData = myCarDataList;
                            carAdapter.setList(myCarDataList);
                        }
                    });
        }
    }

    private void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        carAdapter = new CarAdapter(this);
        mRecyclerView.setAdapter(carAdapter);
    }

    @OnClick(R.id.tv_submit)
    void submit() {
        if (selectCarDataList.size() == 0) {
            ToastUtils.showShortToast("最少选择一件商品");
            return;
        }
        Intent intent = new Intent(this, MakeOrderActivity.class);
        intent.putExtra("carDataList", selectCarDataList);
        intent.putExtra("type", 2);
        startActivity(intent);
    }

    @OnClick(R.id.ll_select)
    void allSelect() {
        selectCarDataList.clear();
        if (isAllSelect) {
            iv_check.setImageResource(R.drawable.wallet_recharge_checkbox);
            isAllSelect = false;
        } else {
            for (CarData myCarData : carData) {
                selectCarDataList.add(myCarData);
            }
            iv_check.setImageResource(R.drawable.address_complete);
            isAllSelect = true;
        }
        count();
        carAdapter.allSelect(isAllSelect);
    }

    public void count() {
        double doubleMoney = 0.00;
        int num = 0;
        if (selectCarDataList.size() > 0) {
            for (int i = 0; i < selectCarDataList.size(); i++) {
                CarData carData = selectCarDataList.get(i);
                for (int j = 0; j < carData.getList().size(); j++) {
                    num++;
                    ShoppingcarDto goods = carData.getList().get(j);
                    doubleMoney += Double.valueOf(goods.getGoodsPay() + goods.getGoodsKtpay()) * goods.getSize();
                }
            }
            doubleGoodsMoney = doubleMoney / 100;
            goodsNum = num;
            if (doubleGoodsMoney < 1) {
                tv_money.setText(0 + df.format(doubleGoodsMoney));
            } else {
                tv_money.setText(df.format(doubleGoodsMoney));
            }
//            tv_money.setText(df.format(doubleMoney));
        } else {
            tv_money.setText("0.00");
        }
        tv_total_num.setText("共计" + num + "件商品 ");
    }

    private void delCar(String shopId, String goodsId) {
        Map<String, String> map = new HashMap<>();
        map.put("token", userInfo.getToken());
        map.put("shoppingCarId", goodsId);
        loadingDialog.show();
        RetrofitClient.getInstance(this)
                .createBaseApi()
                .delCar(map, new BaseSubscriber<ResponseBody>(this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        ToastUtils.showShortToast("网络错误");
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        super.onNext(responseBody);
                        loadingDialog.dismiss();
                        try {
                            String request = responseBody.string();
                            JSONObject json = new JSONObject(request);
                            int code = json.getInt("code");
                            DialogUtils.dismissDialog();
                            if (code == 0) {
                                ToastUtils.showShortToast(json.getString("message"));
                                initData();
                            } else {
                                ToastUtils.showShortToast(json.getString("message"));
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
}
